<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/3/23
 * Time: 13:48
 */

namespace app\admin\controller;

use app\common\bussiness\CategoryBusiness;
use app\common\lib\Tree;
use app\Request;
use think\App;

class Category extends AdminBase
{
    protected $categoryBus = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->categoryBus = new CategoryBusiness();
    }

    public function index()
    {
        try {
            $list = $this->categoryBus->getList();
            $list = Tree::toList($list);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return view('category/index', compact('list'));
    }

    public function create()
    {
        $pid = input("param.pid", 0, "intval");
        // 查询所有分类
        $categories = $this->categoryBus->getList();
        $categories = Tree::toList($categories);

        return view('category/create', compact('pid', 'categories'));
    }

    public function save(Request $request)
    {
        if (!$request->isPost()) {
            $this->error("请求类型不合法");
        }

        $data = $request->post();
        try {
            $res = $this->categoryBus->addCategory($data);
        } catch (\Exception $e) {
            return writeJson(0, $e->getMessage());
        }

        if ($res) {
            return writeJson(1, "分类添加成功");
        }

        return writeJson(0, "分类添加失败");
    }

    public function edit($id)
    {
        $category_one = $this->categoryBus->getCategoryOneById($id);
        $categories   = $this->categoryBus->getList();
        $categories   = Tree::toList($categories);

        return view('category/edit', compact('categories', 'category_one'));
    }

    public function update(Request $request)
    {
        if (!$request->isPost()) {
            return writeJson(0, "请求类型不合法");
        }

        $data = $request->post();
        try {
            $res = $this->categoryBus->updateCategory($data);
        } catch (\Exception $e) {
            return writeJson(0, $e->getMessage());
        }

        if ($res) {
            return writeJson(1, "分类编辑成功");
        }
    }

    public function delete(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(0, "请求类型不合法");
        }

        $id = $request->post('id', 0, 'intval');
        try {
            $result = $this->categoryBus->deleteById($id);
        } catch (\Exception $e) {
            return writeJson(0, $e->getMessage());
        }

        if ($result) {
            return writeJson(1, "分类删除成功");
        }

        return writeJson(0, "分类删除失败");
    }
}